package com.jastar.android.game.richman.logic;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

import com.jastar.android.util.Utils;

public class GameView extends SurfaceView implements SurfaceHolder.Callback, Runnable {

    private SurfaceHolder holder;
    private boolean isRunning;
    private Thread thread;
    public GameManager manager;

    public GameView(Context context) {
        super(context);
        init();
    }

    public GameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public GameView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        holder = getHolder();
        holder.addCallback(this);
    }

    public GameManager getManager() {
        return manager;
    }

    public GameManager initManager(Context context, int playerCount, int money) {
        this.manager = new GameManager(getResources(), playerCount, money);
        this.manager.initLevelHouseIcons(context);
        return this.manager;
    }

    @Override
    public void run() {
        while (isRunning) {
            if (!holder.getSurface().isValid()) continue;

            long s = System.currentTimeMillis();

            Canvas canvas = null;
            try {
                canvas = holder.lockCanvas();
                manager.draw(canvas);
            } finally {
                holder.unlockCanvasAndPost(canvas);
            }

            long e = System.currentTimeMillis();

            long gap = s + 20 - e;
            if (gap > 0) Utils.sleep(gap);

        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isRunning = true;
        thread = new Thread(this);
        thread.start();
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        isRunning = false;
        try {
            thread.join();
        } catch (InterruptedException e) {
            Log.e(getClass().getSimpleName(), "surfaceDestroyed exception.");
        }
    }

}